package repositories

import (
	"babydoge/config/db"
	"babydoge/enum/fileds"
	"babydoge/models"
	"babydoge/processor"
	"gorm.io/gorm"
)

type QueueRepository struct {
	db *db.DB
}

func NewQueueRepository() (queueManager *QueueRepository, err error) {
	var (
		dataBase *db.DB
	)

	if dataBase, err = db.NewDB(); err != nil {
		return &QueueRepository{}, err
	}
	return &QueueRepository{db: dataBase}, err
}

func (repository *QueueRepository) InsertQueue(queue *models.Queue) (id string, err error) {
	var (
		result   *gorm.DB
		jobEvent *processor.JobEvent
	)

	result = repository.db.Db.Create(queue)
	if result.RowsAffected == 1 {
		//TODO 放入到内存中
		jobEvent = &processor.JobEvent{
			EventType: processor.JOB_EVENT_SAVE,
			Job: &processor.Job{
				Name:    queue.ID,
				Command: queue.Command,
				RunAt:   queue.RunAt,
			},
		}
		processor.G_scheduler.HandleJobEvent(jobEvent)
	}

	return queue.ID, result.Error

}

func (repository *QueueRepository) DeleteQueueById(id string) (err error) {
	var (
		result *gorm.DB
	)

	result = repository.db.Db.Model(&models.Queue{ID: id}).UpdateColumns(models.Queue{Status: fileds.Deleted})
	if result.Error == nil {
		processor.G_mux.RLock()
		delete(processor.G_scheduler.JobPlanTable, id)
		processor.G_mux.RUnlock()
	}
	return result.Error
}

func (repository *QueueRepository) AgainQueueById(id string) (err error) {
	var (
		queue models.Queue
		result *gorm.DB
		jobEvent *processor.JobEvent
	)

	result = repository.db.Db.Where("id = ? AND status = ?", id, fileds.Unexecuted).First(&queue)
	if result.Error == nil {
		jobEvent = &processor.JobEvent{
			EventType: processor.JOB_EVENT_SAVE,
			Job: &processor.Job{
				Name:    queue.ID,
				Command: queue.Command,
				RunAt:   queue.RunAt,
			},
		}
		processor.G_scheduler.HandleJobEvent(jobEvent)
	}
	return result.Error
}
